package com.cci.kangdao.escalation.service.impl;

import com.cci.kangdao.aop.UserThreadLocal;
import com.cci.kangdao.dao.CommonNotifyRecordTDao;
import com.cci.kangdao.dao.CompanyTDao;
import com.cci.kangdao.dao.PositionUserTDao;
import com.cci.kangdao.dao.ServiceStationDao;
import com.cci.kangdao.dao.TechDealWithWorkOrderDao;
import com.cci.kangdao.dao.UserTDao;
import com.cci.kangdao.dao.WorkOrderOperatorRelationDao;
import com.cci.kangdao.dao.WorkOrderTDao;
import com.cci.kangdao.dao.model.CommonNotifyRecordT;
import com.cci.kangdao.dao.model.CompanyT;
import com.cci.kangdao.dao.model.PositionUserT;
import com.cci.kangdao.dao.model.UserT;
import com.cci.kangdao.dao.model.WorkOrderT;
import com.cci.kangdao.dto.PagedRequest;
import com.cci.kangdao.dto.PagedResponse;
import com.cci.kangdao.escalation.dao.EscalationFlowTDao;
import com.cci.kangdao.escalation.dao.EscalationOrderTDao;
import com.cci.kangdao.escalation.dao.EscalationReasonTDao;
import com.cci.kangdao.escalation.dao.EscalationSolutionTDao;
import com.cci.kangdao.escalation.dao.PositionExpertEngineerRelationTDao;
import com.cci.kangdao.escalation.dao.PositionExpertTDao;
import com.cci.kangdao.escalation.dto.response.GetEscalationNotifyOrderT;
import com.cci.kangdao.escalation.dto.response.GetNotifyListResponse;
import com.cci.kangdao.escalation.dto.response.GetNotifyResponse;
import com.cci.kangdao.escalation.model.EscalationFlowT;
import com.cci.kangdao.escalation.model.EscalationOrderT;
import com.cci.kangdao.escalation.model.EscalationReasonT;
import com.cci.kangdao.escalation.model.EscalationSolutionT;
import com.cci.kangdao.escalation.service.EscalationNotifyService;
import com.cci.kangdao.fieldService.dto.response.GetItemResponse;
import com.cci.kangdao.service.DictionariesTService;
import com.cci.kangdao.utilTool.BeanUtils;
import com.cci.kangdao.utilTool.CollectionUtils;
import com.cci.kangdao.utilTool.LocalTimeUtil;
import com.cci.kangdao.utilTool.NumberUtils;
import com.cci.kangdao.utilTool.ParameterTool;
import com.cci.kangdao.utilTool.RequestContextHolder;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author William Du
 * @date 2020/5/6
 */
@Service
public class EscalationNotifyServiceImpl implements EscalationNotifyService {

    @Resource
    private EscalationOrderTDao escalationOrderTDao;

    @Resource
    private UserTDao userTDao;

    @Resource
    private WorkOrderOperatorRelationDao workOrderOperatorRelationDao;

    @Resource
    private EscalationFlowTDao escalationFlowTDao;

    @Resource
    private CompanyTDao companyTDao;

    @Resource
    private ServiceStationDao serviceStationDao;

    @Resource
    private CommonNotifyRecordTDao commonNotifyRecordTDao;

    @Resource
    private EscalationReasonTDao escalationReasonTDao;

    @Resource
    private DictionariesTService dictionariesTService;

    @Resource
    private TechDealWithWorkOrderDao techDealWithWorkOrderDao;

    @Resource
    private WorkOrderTDao workOrderTDao;

    @Resource
    private EscalationSolutionTDao escalationSolutionTDao;

    @Resource
    private PositionExpertTDao positionExpertTDao;

    @Resource
    private PositionUserTDao positionUserTDao;

    @Override
    public void notify(Long escalationId) {
        System.out.println("通知" + escalationId);
    }

    @Override
    public Map<String, Object> getEscalationData(Long escalationId) {
        Map<String,Object> dataMap = new HashMap<>();
        EscalationOrderT orderT = escalationOrderTDao.selectByPrimaryKey(escalationId);
        if(null != orderT){
            Map<String,Object> orderMap = BeanUtils.convert(orderT, Map.class);
            dataMap.putAll(orderMap);
            // 用户信息
            UserT creator = userTDao.selectById(orderT.getCreator());
            if(null != creator){
                Map<String,Object> creatorMap = BeanUtils.convert(creator, Map.class);
                dataMap.putAll(creatorMap);
            }

            // 服务工单信息
            WorkOrderT workOrderT = workOrderTDao.getWorkOrderTByOrderId(orderT.getWorkOrderId());
            dataMap.put("complaint",workOrderT.getCustomerComplaint());
            dataMap.put("OEM",workOrderT.getoEMName());
            dataMap.put("ESN",workOrderT.getESN());
            dataMap.put("workOrderNo",workOrderT.getOrderNo());
            EscalationReasonT reasonT = escalationReasonTDao.getLastReasonByOrderId(escalationId);
            StringBuffer reason = new StringBuffer(reasonT.getReasonValue());
            if(StringUtils.isNotEmpty(reasonT.getSupplementReason())){
                reason.append("：").append(reasonT.getSupplementReason());
            }
            dataMap.put("reason",reason.toString());

            // 获取区域信息
            String region = "";
            Map<String, Object> recordMap = workOrderOperatorRelationDao.getOperatorByOrderId(orderT.getWorkOrderId());
            if(MapUtils.isNotEmpty(recordMap)){
                String phone = MapUtils.getString(recordMap, "Phone");
                String crmPositionName = MapUtils.getString(recordMap, "CrmPositionName");
                System.out.println("phone:"+ phone+"crmPositionName:"+crmPositionName+"marketType:"+workOrderT.getMarketType());
                Map<String,Object> positionMap = positionUserTDao.getPositionByPhone(phone,Long.valueOf(workOrderT.getOrderChannel()),crmPositionName,workOrderT.getMarketType());
                region = MapUtils.getString(positionMap,"CrmPositionName");
            }
            dataMap.put("region",region);

            //解决方案
            EscalationSolutionT solutionT = escalationSolutionTDao.getLastEscalationSolutionByOrderId(escalationId);
            if(null != solutionT){
                dataMap.put("solution",solutionT.getSolution());
            }

            // 报单人组织信息
            if(null != creator){
                if(NumberUtils.isPositiveNum(creator.getCompanyId())){
                    CompanyT companyT = companyTDao.getCompanyInfoByCompanyID(creator.getCompanyId());
                    dataMap.put("organization",companyT.getCompanyName());
                }else{
                    Map<String,Object> stationMap = serviceStationDao.getServiceStationById(creator.getServiceStationID());
                    dataMap.put("organization",MapUtils.getString(stationMap,"StationName",""));
                }
            }

            List<EscalationFlowT> flowTList = escalationFlowTDao.getEscalationOrderTimeFlow(escalationId);
            if(CollectionUtils.isNotEmpty(flowTList)){
                dataMap.put("flowType",flowTList.get(0).getType());
            }
        }
        return dataMap;
    }

    @Override
    public List<UserT> getEngineers(Long escalationId) {
        List<UserT> userTList = new ArrayList<>();
        EscalationOrderT orderT = escalationOrderTDao.selectByPrimaryKey(escalationId);
        if (null != orderT) {
            Map<String, Object> recordMap = workOrderOperatorRelationDao.getOperatorByOrderId(orderT.getWorkOrderId());
            String phone = MapUtils.getString(recordMap, "Phone");
            UserT userT = userTDao.getUserByPhone(phone);
            if (null != userT) {
                userTList.add(userT);
            }
        }
        return userTList;
    }

    @Override
    public List<UserT> getTechnicians(Long escalationId) {
        List<UserT> userTList = new ArrayList<>();
        EscalationOrderT orderT = escalationOrderTDao.selectByPrimaryKey(escalationId);
        if (null != orderT) {
            Map<String, Object> recordMap = userTDao.getUserByOrderId(orderT.getWorkOrderId());
            String phone = MapUtils.getString(recordMap, "Phone");
            UserT userT = userTDao.getUserByPhone(phone);
            if (null != userT) {
                userTList.add(userT);
            }
        }
        return userTList;
    }

    @Override
    public List<UserT> getStationMaster(Long escalationId) {
        List<UserT> userTList = new ArrayList<>();
        EscalationOrderT orderT = escalationOrderTDao.selectByPrimaryKey(escalationId);
        if (null != orderT) {
            WorkOrderT workOrderT = workOrderTDao.getWorkOrderTByOrderId(orderT.getWorkOrderId());
            List<UserT> masterList = userTDao.getStationMasterByWorkOrderId(workOrderT.getId());
            userTList.addAll(masterList);
        }
        return userTList;
    }

    @Override
    public List<UserT> getExpert(Long escalationId) {
        List<UserT> expertList = new ArrayList<>();
        List<UserT> engineerList = getEngineers(escalationId);
        EscalationReasonT reasonT = escalationReasonTDao.getLastReasonByOrderId(escalationId);
        if(null != reasonT && CollectionUtils.isNotEmpty(engineerList)){
            Map<String, Object> paramsMap = new HashMap<>();
            paramsMap.put("type", reasonT.getEscalationType());
            paramsMap.put("reasonKey", reasonT.getReasonKey());
            for(UserT engineer : engineerList){
                paramsMap.put("principalPhone", engineer.getPhone());
                List<UserT> dataExpertList = positionExpertTDao.selectPositionExpertByTypeAndReasonKey(paramsMap);
                if(CollectionUtils.isNotEmpty(dataExpertList)){
                    expertList.addAll(dataExpertList);
                }
            }
        }
        return expertList;
    }

    @Override
    public List<UserT> getReasonTypeExpert(Long escalationId) {
        List<UserT> expertList = new ArrayList<>();
        List<UserT> engineerList = getEngineers(escalationId);
        EscalationReasonT reasonT = escalationReasonTDao.getLastReasonByOrderId(escalationId);
        if(null != reasonT && CollectionUtils.isNotEmpty(engineerList)){
            Map<String, Object> paramsMap = new HashMap<>();
            Integer type =  reasonT.getEscalationType();
            if (type == 2 || type == 3) {
                paramsMap.put("reasonType", 2);
            } else if (type == 4 || type == 5 || type == 6) {
                paramsMap.put("reasonType", 1);
            }
            paramsMap.put("reasonKey", reasonT.getReasonKey());
            for(UserT engineer : engineerList){
                paramsMap.put("principalPhone", engineer.getPhone());
                List<UserT> dataExpertList = positionExpertTDao.getReasonTypeExpert(paramsMap);
                if(CollectionUtils.isNotEmpty(dataExpertList)){
                    expertList.addAll(dataExpertList);
                }
            }
        }
        return expertList;
    }


    @Override
    public void getNotifyOrderList(PagedRequest pagedRequest) {
        UserT userT = UserThreadLocal.get();
        // 分页获取工单维度通知列表
        PageHelper.startPage(pagedRequest.getPage(), pagedRequest.getPageSize(), true);
        List<Map<String,Object>>  orderTList = escalationOrderTDao.getOrderListByNotify(userT.getId(),"1");
        PageInfo info = new PageInfo<>(orderTList);
        //处理列表数据
        PagedResponse<GetEscalationNotifyOrderT> response = new PagedResponse<>();
        response.setTotal(info.getTotal());
        List<GetEscalationNotifyOrderT> resultList = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(orderTList)){
            List<Map<String,Object>> statusList = dictionariesTService.getDictionaryList("EscalationOrderStatus");
            Map<String,String> statusMap = new HashMap<>();
            if(CollectionUtils.isNotEmpty(statusList)){
                for(Map<String,Object> map:statusList){
                    Integer dInt = MapUtils.getInteger(map,"DInt");
                    String dValue = MapUtils.getString(map,"DValue");
                    statusMap.put(String.valueOf(dInt),dValue);
                }
            }
            for(Object orderObj:info.getList()) {
                GetEscalationNotifyOrderT notifyOrderT = BeanUtils.convert(orderObj,GetEscalationNotifyOrderT.class);
                String statusStr = String.valueOf(notifyOrderT.getStatus());
                notifyOrderT.setStatusValue(MapUtils.getString(statusMap,statusStr,""));
                if(NumberUtils.isPositiveNum(notifyOrderT.getId())){
                    EscalationReasonT reasonT = escalationReasonTDao.getLastReasonByOrderId(notifyOrderT.getId());
                    if(null != reasonT){
                        notifyOrderT.setReasonValue(reasonT.getReasonValue());
                    }
                }
                resultList.add(notifyOrderT);
            }
        }
        response.setList(resultList);
        ParameterTool.writeSuccessResponse(RequestContextHolder.getResponse(), response);
    }

    @Override
    public void getNotifyList(Long orderId) {
        UserT userT = UserThreadLocal.get();
        EscalationOrderT orderT = escalationOrderTDao.selectByPrimaryKey(orderId);
        List<CommonNotifyRecordT> recordTS = commonNotifyRecordTDao.selectListByOrderId("1",userT.getId(),orderId);
        GetNotifyListResponse response = new GetNotifyListResponse();
        List<GetNotifyResponse> notifyResponseList = BeanUtils.convertList(recordTS,GetNotifyResponse.class);
        if(CollectionUtils.isNotEmpty(notifyResponseList)){
            for(GetNotifyResponse getNotifyResponse : notifyResponseList){
                getNotifyResponse.setWorkOrderId(orderT.getWorkOrderId());
            }
        }
        response.setNotifyList(notifyResponseList);
        ParameterTool.writeSuccessResponse(RequestContextHolder.getResponse(), response);
        // 设置已读该工单通知
        commonNotifyRecordTDao.updatePushReadStatusByReceiverId("1",orderId, userT.getId(), LocalTimeUtil.getRealCurrentTime());
    }
}
